﻿using System.Security.Claims;
using System.Threading.Tasks;
using Hx.Application.Implementation;
using Microsoft.Owin.Security;
using Microsoft.Owin.Security.OAuth;

namespace Hx.WebSite.WebApi.Authorization
{
    public class HaoXueOAuthAuthorizationServerProvider : OAuthAuthorizationServerProvider
    {
        private readonly AuthorImplementation _authorImpl = new AuthorImplementation();

        public override Task ValidateClientAuthentication(OAuthValidateClientAuthenticationContext context)
        {
            string clientId;
            string clientSecret;

            context.TryGetBasicCredentials(out clientId, out clientSecret);
            if (clientId == "WPFClient" && clientSecret == "~!@#WPFClient@#!")
            {
                context.Validated(clientId);
            }

            return base.ValidateClientAuthentication(context);
        }

        public override Task GrantClientCredentials(OAuthGrantClientCredentialsContext context)
        {
            var oAuthIdentity = new ClaimsIdentity(context.Options.AuthenticationType);
            oAuthIdentity.AddClaim(new Claim(ClaimTypes.Name, "WPF App"));
            var ticket = new AuthenticationTicket(oAuthIdentity, new AuthenticationProperties());
            context.Validated(ticket);
            return base.GrantClientCredentials(context);
        }

        public override Task GrantResourceOwnerCredentials(OAuthGrantResourceOwnerCredentialsContext context)
        {
            var author = _authorImpl.CheckLogin(context.UserName, context.Password);
            if (!author.Result)
                return base.GrantResourceOwnerCredentials(context);

            var oAuthIdentity = new ClaimsIdentity(context.Options.AuthenticationType);
            oAuthIdentity.AddClaim(new Claim(ClaimTypes.Name, context.UserName));
            var ticket = new AuthenticationTicket(oAuthIdentity, new AuthenticationProperties());
            context.Validated(ticket);
            return base.GrantResourceOwnerCredentials(context);
        }
    }
}